const http = require("http")
const app = require('./views/router')
const querystring = require('querystring') //node内置模块，把字符串转对象
const ejs = require('ejs')
const {MongoClient} = require('mongodb')
const url = 'mongodb://127.0.0.1:27017';
const dbName = 'School';
const client = new MongoClient(url)

// 注册 web服务
http.createServer(app).listen(3000);

app.static("public");

// 配置路由
app.get('/',function(req,res){
    client.connect((err)=>{
        if(err){
            console.log(err);
            return;
        }
        let db = client.db(dbName)
        // 查询数据
        db.collection("student").find({}).toArray((err,data)=>{
            if(err) {
                console.log(err);
                return;
            } 
            // console.log(data);
            client.close()
            // res.send('首页')
            ejs.renderFile('./views/login.ejs',{list:data},(err,result)=>{
                res.send(result)
            })
        })
    })
})

app.get('/register',function(req,res){
    ejs.renderFile('./views/register.ejs',{},(err,data)=>{
        res.send(data)
    })
})
app.post('/doRegister',function(req,res){
    // console.log(req.body);
    let body = querystring.parse(req.body)

    MongoClient.connect(url,(err,db)=>{
        if(err) throw err;
        let dbase= db.db('School');
        dbase.collection("student").insertOne(body,(err,data)=>{
            if(err) throw err;
            res.send('插入数据成功')
        })
    })
    // res.send(req.body)
})

console.log('http://127.0.0.1:3000/');